<!-- 角色列表 -->
<template>
    <div>
         <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>权限管理</el-breadcrumb-item>
            <el-breadcrumb-item :to="{ path: '/roles' }">角色列表</el-breadcrumb-item>
        </el-breadcrumb>

         <el-card>
             <el-button type="primary">添加角色</el-button>
             <!-- 角色列表 -->
             <el-table
            :data="rolesList" border stripe
            style="width: 100%">
                <!-- 展开列 -->
                <el-table-column type="expand" label="">
                    <template slot-scope="scope">
                        <el-row :class ="['bdbottom',index === 0 && 'bdtop' || '','vcenter']" v-for = "(item,index) in scope.row.children" :key = "item.id">
                            <!-- 一级权限 -->
                            <el-col :span = "5">
                                <el-tag closable @close="handleClose(scope.row,item.id)">{{ item.authName }}</el-tag>
                                <i class="el-icon-caret-right"></i>
                            </el-col>
                            <!-- 二级和三级权限 -->
                            <el-col :span = "19">
                                <el-row :class ="[index2 == 0 ? '' : 'bdtop','vcenter']" v-for = "(item2,index2) in item.children" :key = "item2.id">
                                    <el-col :span = "6">
                                        <el-tag type="success" closable @close="handleClose(scope.row,item2.id)">{{ item2.authName }}</el-tag>
                                         <i class="el-icon-caret-right"></i>
                                    </el-col>
                                    <el-col :span = "18">
                                        <el-tag v-for = "item3 in item2.children" :key = "item3.id" type = "warning" closable @close="handleClose(scope.row,item3.id)">
                                            {{ item3.authName }}
                                        </el-tag>
                                    </el-col>
                                </el-row>
                            </el-col>
                           
                        </el-row>
                    </template>
                </el-table-column>
                <!-- 索引列 -->
                <el-table-column type="index" label="#"></el-table-column>
                <el-table-column 
                    prop="roleName"
                    label="角色名称"
                   >
                </el-table-column>
                <el-table-column
                    prop="roleDesc"
                    label="角色描述"
                    >
                </el-table-column>
                <el-table-column label="操作">
                    <template slot-scope="scope">
                        <el-button type="primary" icon="el-icon-edit" size="mini">编辑</el-button>
                        <el-button type="danger" icon="el-icon-delete" size="mini">删除</el-button>
                        <el-button type="warning" icon="el-icon-setting" size="mini" @click = "showSetRightDialog(scope.row)">分配权限</el-button>
                    </template>
                  
                </el-table-column>
                
            </el-table>
        </el-card>
          <!-- 分配权限的dialog -->
         <el-dialog
            title="提示"
            :visible.sync="rightsDialogVisible"
            width="30%"
            :before-close="closeRightsDialog"
            @close = "setRightsClose"
            >
            <!-- 树形控件 -->
            <el-tree
                :data="rightsList"
                :props="treeProps"
                show-checkbox
                node-key="id"
                default-expand-all
                :default-checked-keys = "defKeys"
                ref = "treeRef"
                >
            </el-tree>
            <span slot="footer" class="dialog-footer">
                <el-button @click="rightsDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="alloRights">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
//这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
//例如：import 《组件名称》 from '《组件路径》';

export default {
//import引入的组件需要注入到对象中才能使用
components: {},
data() {
//这里存放数据
    return {
        rolesList:[],
        rightsDialogVisible: false,
        // 所有权限
        rightsList:[],
        // 树形控件
        treeProps:{
            label:"authName",
            children:"children"
        },
        // 树形控件默认选中的节点
        defKeys:[105,116],
        //分配权限的id
        roleId:""
    };
},
//监听属性 类似于data概念
computed: {},
//监控data中的数据变化
watch: {},
//方法集合
methods: {
    // 角色列表数据
     async getRolesList(){
       const {data} = await this.$http.get("roles")
        if(data.meta.status !==200){
            return this.$message.error("获取角色列表失败");
        }else{
            this.rolesList = data.data;
            // console.log(this.rolesList);
        }
    },  
    // 关闭tag
    handleClose(role,rightId){
        this.$confirm('此操作将永久删除该权限,是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
            // 删除角色指定权限
            const { data } = await this.$http.delete(`roles/${role.id}/rights/${rightId}`);
            // 当前的角色赋值最新的权限
            role.children = data.data;
          this.$message({
            type: 'success',
            message: '已成功删除!'
          });
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });          
        });
    },
    // 分配权限
    async showSetRightDialog(role){
        this.roleId = role.id;
        // 获取所有权限列表
        const {data} = await this.$http.get("/rights/tree");
        this.rightsList = data.data;
        // console.log(this.rightsList);
        this.getKeysId(role,this.defKeys);
        this.rightsDialogVisible = true;
    },
    // 关闭分配权限的dialog
    closeRightsDialog(){
        this.$confirm('确认关闭？')
          .then(() => {
           this.rightsDialogVisible = false;
          })
          .catch(()=>{})
    },
    // 获取三级权限的id
    getKeysId(node,arr){
        if (!node.children) {
            return arr.push(node.id)
        }
        node.children.forEach(item=>{
            this.getKeysId(item,arr)
        })
    },
    // 分配权限的dialog关闭事件
    setRightsClose(){
        this.defKeys = [];
    },
    // 分配权限
    async alloRights(){
        const keys = [
            ...this.$refs.treeRef.getCheckedKeys(),
            ...this.$refs.treeRef.getHalfCheckedKeys()
        ]
        // console.log(keys);
        const idStr = keys.join(",");
        const {data} = await this.$http.post(`roles/${this.roleId}/rights`,{
            rids:idStr
        });
        // console.log(data);
        this.$message.success("分配权限成功!");
        this.rightsDialogVisible = false;

    }
},
//生命周期 - 创建完成（可以访问当前this实例）
created() {
    this.getRolesList();
},
//生命周期 - 挂载完成（可以访问DOM元素）
mounted() {

},
beforeCreate() {}, //生命周期 - 创建之前
beforeMount() {}, //生命周期 - 挂载之前
beforeUpdate() {}, //生命周期 - 更新之前
updated() {}, //生命周期 - 更新之后
beforeDestroy() {}, //生命周期 - 销毁之前
destroyed() {}, //生命周期 - 销毁完成
activated() {}, //如果页面有keep-alive缓存功能，这个函数会触发
}
</script>
<style lang='scss' scoped>
//@import url(); 引入公共css类
 .el-card{
     margin-top: 15px;
 }
 .el-table{
      margin-top: 15px;
 }
.bdtop{
    border-top: 1px solid #eee;
}
.bdbottom{
    border-bottom: 1px solid #eee;
}
 .el-tag{
     margin: 7px;
 }
 .vcenter{
     display: flex;
     align-items: center;
 }
</style>